package com.jmu.posms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.jmu.posms.dao.OrderMapper;
import com.jmu.posms.dto.AddressDto;
import com.jmu.posms.dto.OrderDataDto;
import com.jmu.posms.dto.OrderFormDto;
import com.jmu.posms.dto.OrderInputDto;
import com.jmu.posms.exception.ServiceException;
import com.jmu.posms.pojo.Address;
import com.jmu.posms.pojo.Order;
import com.jmu.posms.pojo.User;
import com.jmu.posms.service.AddressService;
import com.jmu.posms.service.NewspaperService;
import com.jmu.posms.service.OrderService;
import com.jmu.posms.service.UserService;
import com.jmu.posms.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    AddressService addressService;

    @Resource
    OrderMapper orderMapper;

    @Resource
    NewspaperService newspaperService;

    @Resource
    UserService userService;

    Gson gson = new Gson();

    @Override
    @Transactional
    public String add(OrderInputDto inputDto) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if(user==null){
            throw new ServiceException("600","请先登录后操作");
        }

        AddressDto address = new AddressDto();

        address.setName(inputDto.getAddressName());
        address.setPostcode(inputDto.getAddressPostcode());
        address.setTelephone(inputDto.getAddressTelephone());
        address.setRecipient(inputDto.getAddressRecipient());

        Order order = new Order();
        order.setOrderTime(DateUtil.getDate());
        order.setAmount(inputDto.getPrice()*inputDto.getNum());
        order.setId(UUID.randomUUID().toString());

        OrderFormDto orderFormDto = new OrderFormDto(inputDto.getId(),inputDto.getName(),inputDto.getPrice(),inputDto.getPublisher(),inputDto.getNum());

        Gson gson = new Gson();

        String orderForm = gson.toJson(orderFormDto);
        order.setOrderForm(orderForm);

        try{
            order.setUserId(user.getId());
            order.setAddressId(addressService.add(address).getId());
            log.info(order.toString());
            orderMapper.insert(order);
        }catch (Exception e){
            throw new ServiceException("600","购买失败");
        }

        return order.getId();
    }

    private Set<OrderDataDto> findByUserId(String userId, String userName, String newsName, Set<OrderDataDto> outputDtoList){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Order::getUserId,userId);
        List<Order> list = orderMapper.selectList(queryWrapper);

        for (Order order : list) {
            String orderForm = order.getOrderForm();
            OrderFormDto newsForm = gson.fromJson(orderForm, OrderFormDto.class);
            //查找报刊名匹配的
            if(newsForm.getName().equals(newsName)||newsName.equals("")){
                OrderDataDto orderOutput = new OrderDataDto();
                orderOutput.setOrderForm(newsForm);
                orderOutput.setOrderTime(order.getOrderTime());
                orderOutput.setAmount(order.getAmount());
                orderOutput.setId(order.getId());
                orderOutput.setUserName(userName);
                Address address = addressService.getById(order.getAddressId());

                orderOutput.setAddress(address);
                outputDtoList.add(orderOutput);
            }
        }
        return outputDtoList;
    }

    @Override
    public Set<OrderDataDto> find(String userName, String newsName) {
        Set<OrderDataDto> outputDtoList = new HashSet<>();
        if(userName.equals("")){
            List<User> users= userService.list();
            for (User user : users) {
                findByUserId(user.getId(),user.getUserName(),newsName,outputDtoList);
            }
        }else{
            //数据库查找指定用户名
            User user = userService.findByUserName(userName);
            if(user==null){
                return outputDtoList;
            }
            findByUserId(user.getId(),user.getUserName(),newsName,outputDtoList);
        }
        return outputDtoList;
    }

    @Override
    public Set<OrderDataDto> findByNews(String newsName) {
        Set<OrderDataDto> outputDtoList = new HashSet<>();
        //从shiro用户管理器中取出用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        return this.findByUserId(user.getId(), user.getUserName(), newsName,outputDtoList);
    }
}
